package net.sumcraft.mythicmobitemhandler.listener;

import io.lumine.xikage.mythicmobs.api.bukkit.events.MythicMobDeathEvent;
import net.sumcraft.mythicmobitemhandler.util.$;
import net.sumcraft.mythicmobitemhandler.util.ConfigManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;


import java.util.List;

public class MobDeathListener implements Listener {
    @EventHandler
    public void onMythicMobDeath(MythicMobDeathEvent e) {
        if (!(e.getKiller() instanceof Player)) {
            return;
        }
        Player p = (Player) e.getKiller();
        int level = e.getMobLevel();
        List<ItemStack> drops = e.getDrops();
        if (level <= 5) {
            level = 5;
        } else {
            level = (int) (Math.round(level / 5D) * 5);
        }
        for (int i = 0; i < drops.size(); i++) {
            ItemStack itemStack = drops.get(i);
            if (itemStack.getType() == org.bukkit.Material.AIR) {
                continue;
            }
            $.replaceLevel(itemStack, level);
            $.replacePlaceholder(itemStack, p);
            if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasLore()) {
                $.randomLore(itemStack);
            }
            drops.set(i, itemStack);
        }
        if (ConfigManager.drop_to_inv) {
            if (drops.size() > checkNullSpace(p.getInventory())) {
                return;
            }
            for (ItemStack i : drops
                    ) {
                p.getInventory().addItem(i);
            }
            drops.clear();
        }
    }

    private Integer checkNullSpace(Inventory inv) {
        int x = 0;
        for (ItemStack i : inv) {
            if (i == null) {
                x++;
            }

        }
        return x;
    }
}
